<template>
    <!-- 新增编辑弹窗 -->
    <el-dialog v-model="dialogRole" :before-close="onBeforeCancel" width="1000px">
      <template #header>
        <div class="header-title">{{typeRef==1 ? '编辑':'查看'}}堆存费</div>
      </template>
        <el-form ref="formRef" :class="typeRef==2 ? 'diebleIs':''">
              <div class="titie-main">
                <div class="titie-main-fl">堆场堆存信息</div>
              </div>
              <el-table stripe :data="feelList">
                <template v-for="item in columns" :key="item.key">
                  <el-table-column v-if="item.visible" :label="item.label" align="center"
                  :prop="item.key" :fixed="item?.fixed" :width="item?.width">
                  <template v-if="item.slotName=='boxType'" #default="scope">
                      {{ boxTypeOptions[scope.row.boxType] }}
                    </template>
                    <template v-else-if="item.slotName=='boxCondition'" #default="scope">
                      {{ boxCaseOptions[scope.row.boxCondition] }}
                    </template>
                     <template v-else-if="item.slotName=='companyName'" #default="scope">
                      <el-tooltip  class="box-item" effect="dark" :content="scope.row.companyName" placement="top-start" >
                            <div class="nameText"> {{ scope.row.companyName}}</div>
                        </el-tooltip>
                    </template>
                    
                    <template v-else-if="item.slotName=='containerClassify'" #default="scope">
                      {{ boxClassify[scope.row.containerClassify] }}
                    </template>
                    <template v-else-if="item.slotName=='inDate'" #default="scope">
                      {{ formatDate(scope.row.inDate,2)}}
                    </template>
                    <template v-else-if="item.slotName=='outDate'" #default="scope">
                      {{ formatDate(scope.row.outDate,2)}}
                    </template>
                    <template v-else-if="item.slotName=='returnDate'" #default="scope">
                      {{ formatDate(scope.row.returnDate,2)}}
                    </template>
                    <template v-else-if="item.slotName=='sellDate'" #default="scope">
                      {{ formatDate(scope.row.sellDate,2)}}
                    </template>
                    <template v-else-if="item.slotName=='storingOverdueDays'" #default="scope">
                      {{ scope.row.storingOverdueDays || '--'}}
                    </template>           
                    <template v-else-if="item.slotName=='storageFeeCurrency'" #default="scope">
                      <template v-if="scope.row.storageFeeCurrency=='CNY'">人民币（¥）</template>
                      <template v-if="scope.row.storageFeeCurrency=='USD'">美元（$）</template>
                      <!-- <el-select v-model="scope.row.storageFeeCurrency" @change="deductAmountChang" :disabled="typeRef==2">
                        <el-option v-for="item in feeCurrencyList" :key="item.value" :label="item.label" :value="item.value"/>
                      </el-select> -->
                    </template>
                    <template v-else-if="item.slotName=='flex'" #default="scope">
                      <el-input  v-model.trim="scope.row.storageFeePrice" :formatter="formatterNumber" :parser="formatterNumber" @change="overdueFeeDayChang" :disabled="typeRef==2"></el-input>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
              <div class="titie-main">
                <div class="titie-main-fl">{{settlementDirection==1 ? '应收':'应付'}}堆存费费用</div>
                <div class="titie-main-fr">
                  <!-- <el-button :icon="Delete" style="margin:0 20px;" @click="deletList(1)">删除</el-button> -->
                  <el-button type="primary" v-if="typeRef==1" :icon="Plus" style="margin:0;" @click="addList(1)">添加</el-button>
                </div>
              </div>
              <el-table stripe :data="feeDataList">
                <template v-for="item in columnsOne" :key="item.key">
                  <el-table-column v-if="item.visible" :label="item.label" align="center"
                  :prop="item.key" :fixed="item?.fixed" :width="item?.width">
                  <template v-if="item.slotName=='feeCode'" #default="scope">
                    <el-select v-model="scope.row.feeCode" :disabled="scope.row.writeOffStatus==10 || typeRef==2" style="width: 120px" @change	="feeCodeChang($event,scope.$index)" placeholder="请选择费用名称">
                        <el-option
                            v-for="item in filterChang(feeCodeList)"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                      </el-select>
                    </template>
                    <template v-else-if="item.slotName=='deductAmount'" #default="scope">
                      <div style="display: flex;">
                        <el-select v-model="scope.row.feeCurrency" @change="deductAmountChang" :disabled="scope.row.writeOffStatus==10 || typeRef==2 || scope.row.feeCode==35" style="width: 100px" placeholder="请选择币种">
                            <el-option
                                v-for="item in feeCurrencyList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                          </el-select>
                          <el-input
                              v-model.trim="scope.row.deductAmount"
                              placeholder="请输入金额"
                              :formatter="formatterNumber" :parser="formatterNumber"
                              @change	="deductAmountChang"
                              clearable
                              :disabled="scope.row.writeOffStatus==10 || typeRef==2 || scope.row.feeCode==35"
                            style="margin-left: 10px;"
                        />
                      </div>
                      </template>
                    <template v-else-if="item.slotName=='settlementCompanyName'" #default="scope">
                      <div style="display: flex;">
                      <el-select v-model="scope.row.settlementCompanyType" v-if="scope.row.feeCode!=30 && scope.row.feeCode!=35" :disabled="scope.row.writeOffStatus==10 || typeRef==2" style="width: 150px" placeholder="请选择公司类型">
                          <el-option
                              v-for="item in settlementCompanyTypeList"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                          />
                        </el-select>
                        <el-input
                            v-model.trim="scope.row.settlementCompanyName"
                            placeholder="请输入公司名称"
                             :formatter="inputText"
                             maxlength="200"
                            clearable
                            :disabled="scope.row.writeOffStatus==10 || scope.row.feeCode==30 || scope.row.feeCode==35 || typeRef==2"
                            style="margin-left: 10px;"
                        />
                      </div>
                      </template>
                      <template v-else-if="item.slotName=='writeOffStatus'" #default="scope">
                        <span v-if="scope.row.writeOffStatus==5" class="corol-red">未建账单</span>
                        <span v-else-if="scope.row.writeOffStatus==10" class="corol-blue">已建账单</span>
                      </template>
                      <template v-else-if="item.slotName=='remark'" #default="scope">
                        <el-input
                            v-model.trim="scope.row.remark"
                            placeholder="请输入备注信息"
                            :formatter="containsEmoji"
                             maxlength="100"
                            :disabled="scope.row.writeOffStatus==10 || typeRef==2"
                            clearable
                        />
                      </template>
                      <template v-else-if="item.slotName=='flex'" #default="scope">
                        <el-icon v-if="scope.row.writeOffStatus==5" @click="deletList(1,scope.$index)"><Delete /></el-icon>
                      </template>
                    </el-table-column>
                </template>
              </el-table>
              <div class="titie-main">
                <div class="titie-main-fl">费用合计</div>
              </div>
              <div class="tibs">*为您独立计算了应收费用/应付费用中出现的各类币种的各自费用合计</div>
              <div class="fee-main">
                <div class="fee-item tes">总计</div>
                <div class="fee-item" v-if="settlementDirection==1">应收金额：<span class="corol-red">¥{{ form.receivableCnyAmount || 0 }}</span></div>
                <div class="fee-item" v-if="settlementDirection==1">应收金额：<span class="corol-red">${{ form.receivableUsdAmount || 0 }}</span></div>
                <div class="fee-item" v-if="settlementDirection==-1">应付金额：<span class="corol-red">¥{{ form.payableCnyAmount || 0 }}</span></div>
                <div class="fee-item" v-if="settlementDirection==-1">应付金额：<span class="corol-red">${{ form.payableUsdAmount || 0 }}</span></div>
              </div>
              <div class="titie-main">
                <div class="titie-main-fl">备注</div>
                <div class="titie-main-input">
                  <el-input
                    v-model="form.remark"
                    :disabled="typeRef==2"
                    :rows="3"
                    show-word-limit
                    :formatter="containsEmoji"
                    maxlength="100"
                    type="textarea"
                    placeholder="请输入备注信息"
                  />
                </div>
              </div>
         </el-form>
         <template #footer v-if="typeRef==1">
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="onBeforeCancel">取 消</el-button>
            </div>
         </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus,Grid,Delete } from '@element-plus/icons-vue'
import { updateFeeBusinessStoringDetails,selectFeeBusinessStoringDetails } from '@/api/financial/stowageInfo'
import { feeDetails } from '@/api/financial/operatingInfo'
import { formatDate,warTime,formatterNumber ,inputText,containsEmoji} from '@/utils'
const dialogRole=ref(false) //弹框
const feelList=ref([])
const feeDataList=ref([]) //应付//应收
const settlementDirection=ref(1) 
const form=ref({})
const feeCodeList=ref([
  {
    value:5,
    label:'修箱费'
  },{
    value:10,
    label:'提箱费'
  },{
    value:15,
    label:'翻箱费'
  },{
    value:20,
    label:'其他费用'
  },{
    value:25,
    label:'超期费'
  },{
    value:30,
    label:'吊装费'
  },{
    value:35,
    label:'堆存超期费'
  },{
    value:40,
    label:'租入费'
  },{
    value:45,
    label:'租出费'
  },{
    value:50,
    label:'购箱费'
  },{
    value:55,
    label:'卖箱费'
  },{
    value:60,
    label:'箱贴费'
  },
])
const feeCurrencyList=ref([
  {
    value:'CNY',
    label:'¥'
  },
  {
    value:'USD',
    label:'$'
  },
])
const settlementCompanyTypeList=ref([
  {
    value:5,
    label:'客户'
  },
  {
    value:10,
    label:'堆场'
  },
  {
    value:15,
    label:'第三方'
  },
])
const boxTypeOptions=ref({ 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' })
const boxCaseOptions=ref({5: '全新', 10: '次新', 15: '适货', 20: '混提' })
const boxClassify=ref({5: '自有', 10: '代管', 15: '外调'})
// 基础数据
const columns = ref([
  // {key: 'businessNo', label: `业务编号`,  visible: true,},
  {key: 'refNo', label: `箱号`, visible: true,width: 120,},
  {key: 'boxType', label: `箱型`,slotName: 'boxType', visible: true},
  {key: 'boxCondition', label: `箱况`,slotName: 'boxCondition', visible: true},
  {key: 'companyName', label: `集装箱公司`,slotName: 'companyName',  visible: true,width: 150,},
  {key: 'containerClassify', label: `箱源`,slotName: 'containerClassify', visible: true,},
  {key: 'yardName', label: '所在堆场',visible: true,width: 150,},

  {key: 'inDate', label: `进场日期`,slotName: 'inDate', width: 120,visible: true},
  {key: 'outDate', label: `离场日期`,slotName: 'outDate',width: 120, visible: true},
  // {key: 'returnDate', label: `实还箱日期`,slotName: 'returnDate',width: 120, visible: true},
  // {key: 'sellDate', label: `出售日期`,slotName: 'sellDate',width: 120, visible: true},
  // {key: 'carryCityName', label: `提箱城市`, visible: true},
  {key: 'inDays', label: `堆存天数`, visible: true},
  {key: 'storingOverdueDays', label: `超期天数`,slotName: 'storingOverdueDays', visible: true},
  {key: 'storageFeeCurrency', slotName: 'storageFeeCurrency',label: `币种`,fixed: 'right', width: 130, visible: true},
  {key: 'flex', label: `堆存超期费单价(/箱/天)`, slotName: 'flex', fixed: 'right', width: 200, visible: true},

]);
// 列显隐信息
const columnsOne = ref([
  {key: 'feeCode', label: `费用名称`, slotName: 'feeCode', width: 150, visible: true,},
  {key: 'deductAmount', label: `金额`, slotName: 'deductAmount', width: 200, visible: true},
  {key: 'settlementCompanyName', label: `结算单位`, slotName: 'settlementCompanyName',width: 300,  visible: true},
  {key: 'writeOffStatus', label: `状态`, slotName: 'writeOffStatus',visible: true,width: 100, },
  {key: 'remark', label: `备注`, slotName: 'remark',visible: true,width: 200, },
  {key: 'flex', label: `操作`, slotName: 'flex', fixed: 'right', width: 100, visible: true},

]);
const formRef=ref()
const typeRef=ref(1) //1编辑 2查看
const titleType=ref('出租')
const onShow = async (row,type) => {
  dialogRole.value = true
  typeRef.value=type
  settlementDirection.value=row.settlementDirection
  columnsOne.value.map((item)=>{
    if(item.key=='flex'){
      item.visible=type==1 ? true :false
    }
  })
  getRoleDetail(row) 
}
//添加一条数据
const addList=(type)=>{
  // type 1 应收 2应付
    if(feeDataList.value.length==10){
      ElMessage.warning("费用添加最多添加10条");
      return false
    }
    let obj= JSON.parse(JSON.stringify(feeDataList.value[0]))
    Object.keys(obj).forEach(key => {
      obj[key] = null;
    });
    obj.writeOffStatus=5
    obj.feeCurrency='CNY'
    obj.settlementCompanyType=10
    obj.deductAmount=0
    feeDataList.value.push(obj)
}
//删除一条数据
const deletList=(type,index)=>{
  // type 1 应收 2应付
  if(feeDataList.value.length==1){
    ElMessage.warning("至少保留一条费用数据");
    return false
  }
  if(feeDataList.value[index].id==null){
     feeDataList.value.splice(index, 1)
  }else{
      let ids=[]
      ids.push(feeDataList.value[index].id)
     feeDetails(ids).then((res) => {
        feeDataList.value.splice(index, 1)
      })
  }

}
//费用名称改变
const feeCodeChang=(row,index)=>{
  // settlementDirection 1 应收 2应付
    let obj= JSON.parse(JSON.stringify(form.value))
  let isReturn=false
    feeDataList.value[index].feeCode=''
    feeDataList.value.forEach((item)=>{
      if(item.feeCode==row){ if(row==30){
           ElMessage.warning('吊装费不能重复');
          isReturn=true
          return
        }else if(row==35){
           ElMessage.warning('堆存超期费不能重复');
          isReturn=true
          return
        }
      }
      
    })
    if(isReturn){
      return false
    }
    feeDataList.value[index].feeCode=row
    if(row==30 || row==35){
        feeDataList.value[index].settlementCompanyName=obj.companyName
        feeDataList.value[index].settlementCompanyType=10
        if(row==35){
          feeDataList.value[index].feeCurrency=obj.storageFeeCurrency
          feeDataList.value[index].deductAmount=obj.storingOverdueDays*obj.storageFeePrice
          deductAmountChang()
        }
      }else{
         feeDataList.value[index].settlementCompanyName=''
      }
 
}
//超期费用修改
const overdueFeeDayChang=(row)=>{
    let obj= JSON.parse(JSON.stringify(form.value))
  feeDataList.value.forEach((item)=>{
      if(item.feeCode==35){
        item.deductAmount=obj.storingOverdueDays*obj.storageFeePrice
        deductAmountChang()
      }
      
    })
}
//费用合计计算
const deductAmountChang=()=>{
  // type 1 应收 2应付
    let obj= JSON.parse(JSON.stringify(form.value))
  if(settlementDirection.value==1){
    let receivableCnyAmount=0
    let receivableUsdAmount=0
    feeDataList.value.forEach((item)=>{
       if(item.feeCode==35){
        item.feeCurrency=obj.storageFeeCurrency
      } 
      if(item.feeCurrency=='CNY'){
        receivableCnyAmount= Number(item.deductAmount)+receivableCnyAmount
      }else if(item.feeCurrency=='USD'){
        receivableUsdAmount=Number(item.deductAmount)+receivableUsdAmount
      }
    })
    form.value.receivableCnyAmount=receivableCnyAmount.toFixed(2)
    form.value.receivableUsdAmount=receivableUsdAmount.toFixed(2)
  }else{
    let payableCnyAmount=0
    let payableUsdAmount=0
    console.log('feeDataList.value',feeDataList.value)
    feeDataList.value.forEach((item)=>{
       if(item.feeCode==35){
        item.feeCurrency=obj.storageFeeCurrency
      }
      if(item.feeCurrency=='CNY'){
        payableCnyAmount=Number(item.deductAmount)+payableCnyAmount
      }else if(item.feeCurrency=='USD'){
        payableUsdAmount=Number(item.deductAmount)+payableUsdAmount
      }  
    })
    form.value.payableCnyAmount=payableCnyAmount.toFixed(2)
    form.value.payableUsdAmount=payableUsdAmount.toFixed(2)
  }
}

const emits = defineEmits(['updateMode'])
/** 提交按钮 */
const submitForm = () =>{
  //判断费用类型不能重复
  let data= JSON.parse(JSON.stringify(form.value))
let isReturn=false
let tiletStus=settlementDirection.value==1 ? '应收':'应付'
 feeDataList.value.forEach((item)=>{
    if (!item.feeCode) {
      ElMessage.warning(tiletStus+'堆存费用费用名称不能为空');
      isReturn=true
      return
    }else if(!item.settlementCompanyName){
      ElMessage.warning(tiletStus+'堆存费用结算单位不能为空');
       isReturn=true
      return
    }else if(!item.deductAmount && item.deductAmoun!=0){
      ElMessage.warning(tiletStus+'堆存费用金额不能为空且不能为0');
       isReturn=true
      return
    }
  })
  if(settlementDirection.value==1){
    data.receivableFeeDetailsList=feeDataList.value
    data.payableFeeDetailsList=[]
  }else{
    data.payableFeeDetailsList=feeDataList.value
    data.receivableFeeDetailsList=[]
  }
  if(isReturn){
    return false
  }
    updateFeeBusinessStoringDetails(data).then(response => {
       emits('updateMode');
          ElMessage.success('编辑成功');
          cancel();
    });
};
//关闭弹框
const cancel = () => {
  dialogRole.value=false
}
//取消
const onBeforeCancel = () => {
  if(typeRef.value==1){
    ElMessageBox.confirm('您确定要关闭当前编辑窗口，请注意保存已修改信息').then(function () {
    }).then(() => {
      cancel()
    })
    .catch(() => {
    });
  }else{
    cancel()
  }
}
//详情查询
const getRoleDetail=(row)=>{
  let data={
    businessId:row.businessId,
    settlementDirection:row.settlementDirection
  }
  selectFeeBusinessStoringDetails(data).then(res => {
    // receivableFeeDetailsList.value=res.data.receivableFeeDetailsList
    // payableFeeDetailsList.value=res.data.payableFeeDetailsList
    form.value=res.data
    let listData=[]
    listData.push(res.data)
    if(settlementDirection.value==1){
      feeDataList.value=res.data.receivableFeeDetailsList
      // receivableFeeDetailsList.value=res.data.receivableFeeDetailsList
      // form.value.receivableFeeDetailsList=[]

      // form.value.receivableFeeDetailsList=res.data.receivableFeeDetailsList
      //  form.value.payableFeeDetailsList=[]
      
    }else{
      feeDataList.value=res.data.payableFeeDetailsList

      // receivableFeeDetailsList.value=res.data.payableFeeDetailsList
      // form.value.receivableFeeDetailsList=res.data.payableFeeDetailsList
      // form.value.payableFeeDetailsList=[]
      // form.value.payableFeeDetailsList=[]

    }
    feelList.value=listData
    // if(res.data.refType==5){
    //   titleType.value='出租'
    // }else if(res.data.refType==10){
    //   titleType.value='回调'

    // }else if(res.data.refType==20){
    //   titleType.value='出售'
    // }
  })
}
//过滤列是否显示
// const filterColumns=(list)=>{
//   let columnsList=[]
//   if(form.value.refType==5 || form.value.refType==10){
//     columnsList=list.filter(person => person.key != 'sellDate')
//   }else if(form.value.refType==20){    
//     columnsList=list.filter(person => person.key != 'outDate' && person.key != 'shouldReturnDate' && person.key != 'returnDate')
//   }
//   return columnsList
// }
//过滤数据
const filterChang=(list)=>{
  let listCode=[]
    listCode=list.filter(person => person.value <= 35)

  // if(form.value.refType==5){
  //   listCode=list.filter(person => person.value != 50 && person.value != 55 && person.value != 60)
  // }else if(form.value.refType==10){
  // listCode=list.filter(person => person.value != 40 && person.value != 45 && person.value != 50 && person.value != 55)
  // }else if(form.value.refType==20){    
  //   listCode=list.filter(person => person.value != 40 && person.value != 45 && person.value != 60)
  // }
  return listCode
}
defineExpose({ onShow })
</script>

<style scoped>
.corol-red{
  color: #FF4242;
}
.corol-blue{
  color: #0364FF;
}
.titie-main{
  display: flex;
  justify-content: space-between;
  align-content: center;
  margin: 10px 0;
}
.titie-main-fl{
  color: #121317;
}
.tibs{
  color: #2158F3;
  font-size: 12px;
}
.fee-main{
  display: flex;
  border: 1px solid #eeeeee;
  margin-top: 10px;
}
.fee-item.tes{
  border-right:1px solid #eeeeee ;
}
.fee-item{
  margin-right: 20px;
  padding: 10px 20px;
}
.titie-main-input{
  flex: 1;
  margin-left: 20px;
}
.header-title{
  border-left: 4px solid #2158F3;
  padding-left: 8px;
  line-height: 18px;
}
.nameText{
  display:-webkit-box;
	overflow:hidden;
	-webkit-box-orient:vertical;
	-webkit-line-clamp:2; 
}

</style>